package com.shure.utils;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlTagCloser {

    // 需要强制闭合的标签集合
    private static final Set<String> TAGS_TO_CLOSE = new HashSet<String>() {{
        add("area");
        add("base");
        add("br");
        add("col");
        add("embed");
        add("hr");
        add("img");
        add("input");
        add("link");
        add("meta");
        add("param");
        add("source");
        add("track");
        add("wbr");
    }};

    public static String forceCloseTags(String html) {
        if (html == null) return html;

        // 匹配目标标签（包括自闭合形式）
        Pattern pattern = Pattern.compile(
                "<(" + String.join("|", TAGS_TO_CLOSE) + ")(?![a-zA-Z])([^>]*)(/?)>",
                Pattern.CASE_INSENSITIVE
        );

        Matcher matcher = pattern.matcher(html);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String tagName = matcher.group(1).toLowerCase();
            String attributes = matcher.group(2);
            if (attributes.endsWith("/")) {
                attributes = attributes.substring(0, attributes.length() - 1);
            }

            // 移除结尾的/，然后添加闭合标签
            String replacement = "<" + tagName + attributes + "></" + tagName + ">";
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static void main(String[] args) {
        String html = "<br><hr><img src='test.jpg'><p>Text</p><img src='x.jpg' width='200' />";
        System.out.println("原始HTML:\n" + html);
        System.out.println("处理后HTML:\n" + forceCloseTags(html));
    }
}